<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\model\Sms;
use app\model\User;
use think\Request;

class SmsController extends BaseController
{
	/**
	 * 发送验证码
	 * event 验证码类型:登录=login,注册=register,换绑手机号=changemobile,更改密码=changepwd,重置密码=resetpwd
	 * @param Request $request
	 */
	function send(Request $request)
	{
		$params = $request->param();
		$event = $params['event'] ?? 'register';
		
		try {
			validate(\app\validate\Sms::class)->check($params);
		} catch (\Exception $e) {
			$this->writeJson(0,$e->getMessage());
		}
		$ipSendTotal = Sms::where(['ip' => $request->ip()])->whereTime('createtime', '-1 hours')->count();
		$last = Sms::where(['mobile' => $params['mobile'], 'event' => $event])->order('id', 'DESC')->find();
		if (($last && time() - $last->createtime < 60) || $ipSendTotal >= 10) {
			$this->writeJson(0,'发送频繁');
		}
		if ($event) {
			$userinfo = User::getByMobile($params['mobile']);
			if ($event == 'register' && $userinfo) {
				//已被注册
				$this->writeJson(0, '已被注册');
			} elseif ($event == 'changemobile' && $userinfo) {
				//被占用
				$this->writeJson(0, '已被占用');
			} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
				//未注册
				$this->writeJson(0, '未注册');
				
			}
		}
		
		$ret = \app\common\Sms::send($params['mobile'],null, $event);
		if ($ret) {
			$this->writeJson();
		} else {
			$this->writeJson(0, '发送失败');
		}
	}
}
